/**
 * 登录后员工信息以及对应的菜单信息
 * 
 * @param {}
 *            id 员工ID
 * @param {}
 *            name 员工姓名
 * @param {}
 *            postId 岗位ID
 * @param {}
 *            deptId 部门ID
 * @param {}
 *            rights 功能菜单
 * @param {}
 *            topMenu 顶级菜单
 */
var UserInfo = function(id, name, postId, isSubscription, userSubscriber,
		deptId, rights, topMenu,socketUrl) {
	this.userId = id;
	this.userName = name;
	this.postId = postId;
	this.deptId = deptId;
	this.isSubscription = isSubscription;
	this.userSubscriber = userSubscriber;
	this.rights = rights;
	this.topMenu = topMenu;
	this.socketUrl=socketUrl;
};
/**
 * 员工信息全局变量
 * 
 * @type
 */
var curUserInfo = null;
/**
 * 按钮权限控制
 * 
 * @class Ext.scm.Button
 * @extends Ext.Button
 */
Ext.namespace('Ext.scm')
Ext.scm.Button = Ext.extend(Ext.Button, {
			initComponent : function() {
				Ext.scm.Button.superclass.initComponent.call(this);
				var arr = curUserInfo.rights;
				this.hsHideFn(arr);
			},
			hsHideFn : function(arr) {
				if (arr.indexOf(this.hsValue) != -1) {
					this.show();
				}
			},
			hidden : true
		});
Ext.reg('privilegeButton', Ext.scm.Button);

// 根据用户权限判断按钮是否显示
function isGranted(buttonName) {
	if (curUserInfo.rights.indexOf("_ALL") != -1) {
		return true;
	}
	if (curUserInfo.rights.indexOf(buttonName) != -1) {
		return true;
	}
	return false;
};
/**
 * 主页面框架
 * 
 * @class IndexPage
 * @extends Ext.Viewport
 */
IndexPage = Ext.extend(Ext.Viewport, {
	top : new Ext.Panel({
				region : "north",
				id : "__nortPanel",
				contentEl : "app-header",
				height : 40
			}),
	center : null,
	west : new Ext.Panel({
				region : "west",
				id : "west-panel",
				title : "导航",
				iconCls : "menu-navigation",
				split : true,
				width : 200,
				autoScroll : false,
				layout : "accordion",
				collapsible : true,
				items : []
			}),
	constructor : function() {
		this.center = new Ext.TabPanel({
					id : "centerTabPanel",
					region : "center",
					deferredRender : true,
					enableTabScroll : true,
					minButtonWidth : 200,
					activeTab : 0,
					defaults : {
						autoScroll : false,
						boder : true,
						closable : true
					},
					items : [],
					listeners : {
						"add" : function(c, a, b) {
							if (c.items.length >= 8) {
								c.remove(c.items.get(0));
								c.doLayout();
							}
						}
					},
					plugins : new Ext.ux.TabCloseMenu()
				});
		IndexPage.superclass.constructor.call(this, {
					layout : "border",
					items : [this.top, this.west, this.center]
				});
		this.afterPropertySet();
	},
	afterPropertySet : function() {
		var c = this.center;
		var b = getCookie("_topNavId");
		if (b == null || b == undefined) {
			b = 0;
		}
		var a = new Ext.TabPanel({
					id : "appNavTabPanel",
					deferredRender : true,
					enableTabScroll : false,
					activeTab : b,
					frame : false,
					border : false,
					plain : true,
					height : 0,
					autoWidth : true,
					monitorResize : true,
					renderTo : "navHeader",
					tabMargin : 20,
					defaults : {
						autoScroll : false,
						closable : false
					},
					listeners : {
						scope : this,
						"tabchange" : function(j, i) {
							var h = new Date();
							h.setDate(h.getDate() + 3);
							setCookie("_topNavId", i.getId(), h, __ctxPath);
							this.loadWestMenu(i.getId());
						}
					},
					items : []
				});
		a.add(curUserInfo.topMenu);
		var e = getCookie("_topNavId");
		if (e) {
			a.activate(e);
		}
		if (a.getActiveTab() == null) {
			a.activate(a.items.get(0));
		}
	},
	loadWestMenu : function(id) {
		var westPanel = Ext.getCmp("west-panel");
		Ext.Ajax.request({
					url : __ctxPath + "/systemMenu/selectLeftMenu",
					method : "post",
					params : {
						id : id
					},
					success : function(response, options) {
						westPanel.removeAll();
						westPanel.doLayout();
						var arr = eval(response.responseText);
						var child = arr[0].children;
						var __activedPanelId = getCookie("__activedPanelId");
						if (typeof(child) != "undefined") {
							for (var i = 0; i < child.length; i++) {
								var panel = new Ext.tree.TreePanel({
											id : child[i].id,
											title : child[i].text,
											url : child[i].url,
											layout : "fit",
											animate : true,
											autoScroll : true,
											loader : new Ext.tree.TreeLoader({
														preloadChildren : true
													}),
											root : new Ext.tree.AsyncTreeNode({
														children : child[i].children
													}),
											listeners : {
												"click" : function(a) {
													App.clickNode(a, id);
												}
											},
											rootVisible : false
										});
								westPanel.add(panel);
								panel.on("expand", function(p) {
											var expires = new Date();
											expires.setDate(expires.getDate()
													+ 3);
											setCookie("__activedPanelId", p.id,
													expires, __ctxPath);
											this.root.expand(true);
										});
								if (child[i].id == __activedPanelId) {
									westPanel.layout.activeItem = panel;
								}
							}
						}
						westPanel.doLayout();
						westPanel.layout.activeItem.expandAll();
					}
				});
	}
});
Ext.ns("App");
// 初始化
App.init = function() {
	Ext.QuickTips.init();
	Ext.BLANK_IMAGE_URL = __ctxPath + "/ext/resources/images/default/s.gif";
	Ext.DEFAULT_IMAGE_URL = __ctxPath + "/images/monmonde.png";
	setTimeout(function() {
				Ext.get("loading").remove();
				Ext.get("loading-mask").fadeOut({
							remove : true
						});
			}, 100);
	Ext.Ajax.defaultHeaders = {// Default headers to pass in every request
		'Request-By' : 'Ext' // 标识ajax请求
	};

	// ajax回调函数处理系统退出
	Ext.Ajax.on('requestcomplete', checkSessionStatus, this);
	function checkSessionStatus(conn, response, options) {
		var returnVal = response.responseText;
		if (!Ext.isEmpty(returnVal)
				&& returnVal.indexOf('SessionExpired') != -1) {
			var json = Ext.decode(returnVal);
			if (typeof !json.success && json.timeout) {
				Ext.MessageBox.alert("登录超时,系统将自动跳转到登陆页面,请重新登入!");
				top.window.location.href = __ctxPath + "/login.jsp";
			}
		}
		if (!Ext.isEmpty(returnVal) && returnVal.indexOf('exceptionMsg') != -1) {
			var json = Ext.decode(returnVal);
			if (typeof !json.success && json.exception) {
				Ext.MessageBox.alert("操作出错：", json.exceptionMsg);
			}
		}
	}
	Ext.Ajax.request({
				url : __ctxPath + "/systemMenu/selectTopMenu",
				method : "post",
				success : function(response, config) {
					var d = Ext.util.JSON.decode(response.responseText);
					if (d.menu.list != null) {
						curUserInfo = new UserInfo(d.userId, d.userName,
								d.postId, d.isSubscription, d.userSubscriber,
								d.deptId, d.rights, d.menu.list,d.socketUrl);
						new IndexPage();
					}
					// 如果登录用户是生产部并且需要订阅消息则链接消息服务
					if (d.isSubscription == "1") {
						connectionSocket();
					}
				}
			});

	Ext.getDoc().on('keydown', function(e) {
		if (e.getKey() == 8 && e.getTarget().type == 'text'
				&& !e.getTarget().readOnly) {
			return;
		} else if (e.getKey() == 8 && e.getTarget().type == 'textarea'
				&& !e.getTarget().readOnly) {
			return;
		} else if (e.getKey() == 8 && e.getTarget().type == 'password'
				&& !e.getTarget().readOnly) {
			return;
		} else if (e.getKey() == 8) {
			e.preventDefault();
		}
	});

	var storeTheme = getCookie('theme');
	if (storeTheme == null || storeTheme == '') {
		storeTheme = 'ext-all';
	}
	Ext.util.CSS.swapStyleSheet("theme", __ctxPath + "/ext/resources/css/"
					+ storeTheme + ".css");
	/**
	 * 菜单颜色选择
	 */
	new Ext.form.ComboBox({
		renderTo : "welcomeMsg",
		mode : "local",
		editable : false,
		value : "切换皮肤",
		width : 80,
		triggerAction : "all",
		store : [["ext-all", "缺省浅蓝"], ["ext-all-css03", "粉红主题"],
				["ext-all-css04", "灰白主题"], ["xtheme-default2", "灰蓝主题"],
				["xtheme-tp", "灰色主题"], ["ext-all-css05", "绿色主题"],
				["xtheme-access", "Access风格"]],
		listeners : {
			scope : this,
			"select" : function(d, b, c) {
				if (d.value != "") {
					var a = new Date();
					a.setDate(a.getDate() + 300);
					setCookie("theme", d.value, a, __ctxPath);
					Ext.util.CSS.swapStyleSheet("theme", __ctxPath
									+ "/ext/resources/css/" + d.value + ".css");
				}
			}
		}
	});
	// grid可复制
	if (!Ext.grid.GridView.prototype.templates) {
		Ext.grid.GridView.prototype.templates = {};
	}
	Ext.grid.GridView.prototype.templates.cell = new Ext.Template(
			'<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>',
			'<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>',
			'</td>');
};
// 菜单点击事件
App.clickNode = function(a, id) {
	var centerPanel = Ext.getCmp("centerTabPanel");
	var westPanel = Ext.getCmp("west-panel").layout.activeItem;
	var parentId = a.attributes.parentId;
	var loadType = a.attributes.loadType;
	var tab = centerPanel.getItem(a.id);
	if (a.leaf) {// 叶子节点
		if (tab == null) {
			if (loadType == 'jsp') {
				tab = centerPanel.add({
							id : a.id,
							title : a.attributes.text,
							closable : true,
							autoScroll : false,
							layout : "anchor",
							autoLoad : {
								url : __ctxPath + a.attributes.url,
								scripts : true,
								scope : this
							}
						});
				centerPanel.activate(tab);
			} else {
				tab = centerPanel.add({
							id : a.id,
							title : a.attributes.text,
							closable : true,
							autoScroll : false,
							layout : 'anchor'
						});
				centerPanel.activate(tab);
				Ext.Loader.load([__ctxPath + a.attributes.url], function() {
						});
			}
		} else {
			centerPanel.activate(tab);
		}
	}
};
// 退出系统
App.Logout = function() {
	Ext.Ajax.request({
				url : __ctxPath + "/systemUser/loginout",
				method : "post",
				success : function() {
					window.location.href = __ctxPath + "/login.jsp";
				}
			});
			
};
// 修改密码
App.UpdatePassword = function(userId) {
	new UpdatePasswordForm({
				adminName : userId
			}).show();
}
// 订阅或取消订阅操作
App.subscriptionRemind = function(isSubscription, value) {
	Ext.Msg.confirm("信息确认", "您确定要" + value + "吗？", function(c) {
		if (c == "yes") {
			var myMask = new Ext.LoadMask(Ext.getBody(), {
						msg : "正在处理,请稍后..."
					});
			myMask.show();
			Ext.Ajax.request({
						url : __ctxPath
								+ '/systemAdmin/updatePriAdminSubscription',
						params : {
							isSubscription : isSubscription
						},
						method : "post",
						success : function(response, config) {
							myMask.hide();
							var jsonData = Ext.util.JSON
									.decode(response.responseText);
							if (jsonData.success) {
								var subscriptionRemind = document
										.getElementById("subscriptionRemindMsg");
								if (isSubscription == 0) {
									if (subscriptionRemind) {
										subscriptionRemind.innerHTML = "订阅消息";
										curUserInfo.isSubscription = "0";
										subscriptionRemind.onclick = function() {
											App.subscriptionRemind(1, '订阅消息');
										};
									}
								} else {
									if (subscriptionRemind) {
										subscriptionRemind.innerHTML = "取消订阅消息";
										curUserInfo.isSubscription = "1";
										// 链接消息推送
										connectionSocket();
										subscriptionRemind.onclick = function() {
											App.subscriptionRemind(0, '取消订阅消息');
										};
									}
								}
							} else {
								Ext.MessageBox.show({
											title : "错误提示",
											msg : value + "失败!",
											buttons : Ext.MessageBox.OK,
											icon : Ext.MessageBox.ERROR
										});
							}
						},
						failure : function(response, config) {
							myMask.hide();
							Ext.MessageBox.show({
										title : "错误提示",
										msg : "服务器请求错误,请稍后再试!",
										buttons : Ext.MessageBox.OK,
										icon : Ext.MessageBox.ERROR
									});
						}
					});
		}
	});
};

/**
 * 查看确认订单信息
 */
App.lookOrderConfirmDetail = function() {
	var centerPanel = Ext.getCmp("centerTabPanel");
	var tab = centerPanel.getItem(PmsUtil.ORDER_CONFIRM_QUERY_ID);
	var createNewTab = new CreatNewTab(PmsUtil.ORDER_CONFIRM_QUERY_ID, '已确认订单');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['queryOrderConfirmedForm','orderConfirmedManagerGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/order/orderConfirmed.js'],
			function() {
			});
}
/**
 * 登录成功后获取消息推送链接
 */
function connectionSocket() {
	// 连接推送服务器
	var socket = io.connect(curUserInfo.socketUrl);
	// 连接成功发送消息
	socket.on('connect', function() {
				socket.emit('userInfo', {
							id : curUserInfo.userId
						});
			});
	// 当接收到推送的数据后显示到页面
	socket.on('sendmessage', function(data) {
				if (curUserInfo.isSubscription == "1") {
					var subscriberType = data.subscriberType;
					var arraySub = curUserInfo.userSubscriber.split(",");
					for (i = 0; i < arraySub.length; i++) {
						if (arraySub[i] == subscriberType) {
							new Pop(data.orderId,data.title,data.content);
							break;
						}
					}
				}
			});
	// 接收未处理提醒任务
	socket.on('ordercount', function(data) {
		var content = data.content;
		if (document.getElementById("unSetttledRemindMsg")) {
			if (curUserInfo.isSubscription == "1") {
				var subscriberType = data.subscriberType;
				var arraySub = curUserInfo.userSubscriber.split(",");
				for (i = 0; i < arraySub.length; i++) {
					if (arraySub[i] == subscriberType) {
						if (window.navigator.userAgent.toLowerCase()
								.indexOf('msie') >= 1) {
							document.getElementById("unSetttledRemindMsg").innerText = "你有"
									+ content + "条待处理订单";
						} else {
							document.getElementById("unSetttledRemindMsg").textContent = "你有"
									+ content + "条待处理订单";
						}
						break;
					}
				}
			}

		}
	});
};
// 获得centerTabPanel
App.getContentPanel = function() {
	var a = Ext.getCmp("centerTabPanel");
	return a;
};
// 删除centerTabPanel的item
App.removeTab = function(a) {
	var b = App.getContentPanel();
	var c = b.getItem(a);
	if (c != null) {
		b.remove(c, true);
	}
};
// 验证字符串是否为空 @author:hejinguo
App.isEmpty = function(obj) {
	return Ext.isEmpty(Ext.util.Format.trim(obj));
};

// 修改密码窗口
UpdatePasswordForm = Ext.extend(Ext.Window, {
	formPanel : null,
	constructor : function(a) {
		Ext.applyIf(this, a);
		this.initUIComponents();
		UpdatePasswordForm.superclass.constructor.call(this, {
					layout : "fit",
					items : this.formPanel,
					border : false,
					modal : true,
					plain : true,
					id : "UpdatePasswordFormWin",
					title : "修改密码",
					width : 300,
					height : 180,
					minWidth : 300,
					minHeight : 180,
					bodyStyle : "padding:5px;",
					buttonAlign : "center",
					buttons : this.buttons
				});
	},
	initUIComponents : function() {
		this.formPanel = new Ext.FormPanel({
					url : __ctxPath + "/systemUser/updatePassWord",
					layout : "form",
					id : "UpdatePasswordForm",
					frame : true,
					defaults : {
						widht : 400,
						anchor : "100%,100%"
					},
					defaultType : "textfield",
					items : [{
								xtype : "hidden",
								id : "uname",
								name : "uname",
								value : this.adminName == null
										? ""
										: this.adminName
							}, {
								xtype : "textfield",
								allowBlank : false,
								blankText : "旧密码不能为空...",
								inputType : "password",
								id : "oldPass",
								name : "oldPass",
								fieldLabel : "旧密码"
							}, {
								xtype : "textfield",
								allowBlank : false,
								blankText : "新密码不能为空...",
								inputType : "password",
								id : "newPass",
								name : "newPass",
								fieldLabel : "新密码"
							}, {
								xtype : "textfield",
								allowBlank : false,
								inputType : "password",
								id : "pass",
								name : "pass",
								fieldLabel : "确认密码"
							}]
				});
		this.buttons = [{
			text : "保存",
			handler : function() {
				var b = Ext.getCmp("UpdatePasswordForm");
				if (b.getForm().isValid()) {
					b.getForm().submit({
								method : "post",
								waitTitle : "请稍候",// "请稍候",
								waitMsg : "正在提交表单，请稍候......",// "正在提交表单，请稍候......",
								success : function(c, d) {
									Ext.MessageBox.show({
												title : "操作提示",
												msg : d.result.data,
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.INFO
											});
									Ext.getCmp("UpdatePasswordFormWin").close();
								},
								failure : function(c, d) {
									Ext.MessageBox.show({
												title : "操作信息",
												msg : d.result.data,
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
								}
							});
				}
			}
		}, {
			text : "取消",
			handler : function() {
				Ext.getCmp("UpdatePasswordFormWin").close();
			}
		}];
	}
});

function setCookie(b, d, a, f, c, e) {
	document.cookie = b + "=" + escape(d)
			+ ((a) ? "; expires=" + a.toGMTString() : "")
			+ ((f) ? "; path=" + f : "") + ((c) ? "; domain=" + c : "")
			+ ((e) ? "; secure" : "");
}
function getCookie(b) {
	var d = b + "=";
	var e = document.cookie.indexOf(d);
	if (e == -1) {
		return null;
	}
	var a = document.cookie.indexOf(";", e + d.length);
	if (a == -1) {
		a = document.cookie.length;
	}
	var c = document.cookie.substring(e + d.length, a);
	return unescape(c);
}
function deleteCookie(a, c, b) {
	if (getCookie(a)) {
		document.cookie = a + "=" + ((c) ? "; path=" + c : "")
				+ ((b) ? "; domain=" + b : "")
				+ "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}